<?php

namespace app\admin\controller\card;

use app\common\controller\Backend;
use app\common\model\Merchant;
use app\common\model\Merchantgoods;
use Exception;
use fast\Tree;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 洗车类型
 *
 * @icon fa fa-circle-o
 */
class Type extends Backend
{

    /**
     * Type模型对象
     * @var \app\common\model\card\Type
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\card\Type;
        //获取数据并转成数组
        $list = collection($this->model->select())->toArray();
        //将数据给到这个方法中
        Tree::instance()->init($list);
        //这创建了一个空数组，然后使用 getTreeList() 方法从 Tree 实例中检索一组树节点
        //将根节点 ID (0) 作为参数传递给它的 getTreeArray() 方法。
        $groupdata = [];
        $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        //遍历 $result 数组，将每个树节点的 name 字段作为 $groupdata 数组中一个条目的值，将 id 字段作为键。
        foreach ($result as $k => $v) {
            $groupdata[$v['id']] = $v['name'];
        }
        //返回
        $this->view->assign("statusList", $groupdata);
    }

    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        //判断请求为Ajax
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //查询数据库获得结果
            $list = $this->model

                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            //初始化并传入结果
            Tree::instance()->init($list);
            $groupdata = [];
            //获取树形结构列表
            $result1 = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            //返回值
            $result = array("total"=>$list->total(),"rows"=>$result1);
            //返回
            return json($result);
        }
        return $this->view->fetch();
    }

    public function selectpage2(){
        //获取树形结构列表
        $result1 = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        //返回值
        $result = array("total"=>count($result1),"rows"=>$result1);
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $pid=!$this->request->param("pid")?0:$this->request->param("pid");
            $this->assign("pid",$pid);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        $res=$this->check($params);
        if(!$res) return $res;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        $res=$this->check($params,$ids);
        if(!$res) return $res;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            if($row["name"]!=$params["name"]){
                \app\common\model\card\Kabawtype::where(["card_type_id"=>$ids])->update(["card_type_name"=>$params["name"]]);
            }
            if($params["price"]!=$row["price"]){
                //修改了最高限价
                Merchantgoods::where(["card_type_id"=>$row["id"]])->update(["highest_price"=>$params["price"]]);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    protected function check($params,$ids=0){
        $data=[
            ['name', 'require|unique:cardType', '名称不能为空|该名称已存在'],
            ['price', 'require', '最高限价不能为空'],
        ];
        if(!empty($ids)){
            $data[0]=['name', 'require|unique:cardType,name,' .$ids, '名称不能为空|该名称已存在'];
        }
        $validate = new \think\Validate($data);
        if (!$validate->check($params)) {
            $this->error('提交失败：' . $validate->getError());
        }
        if($params["price"]<=0) $this->error("请填写小于0的数");
        return true;
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $kabaw = \app\common\model\card\Kabawtype::where("card_type_id", 'in', $ids)->select();
        if(!empty($kabaw)) $this->error("该类型下有关联的卡卷包，若要删除，请先删除卡卷包!");
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                if($item["pid"]==0){
                    $this->model->where(["pid"=>$item["id"]])->delete();//删除二级分类
                }
                $count += $item->delete();
                Merchantgoods::where(["card_type_id"=>$item["id"]])->delete();//删除店铺商品
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
